package com.keta.foundation.dataFilter;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.lang3.StringUtils;

public class DataFilter {

	// 分隔符
	public static final String DataFilterSeparator = "_";

	/**
	 * EQ, 等于 NEQ, 不等于 LIKE, 模糊查询 GT, 大于 LT 小于 GTE 大于等于 LTE 小于等于 IN in操作
	 */
	public enum Operator {
		EQ, NEQ, LIKE, GT, LT, GTE, LTE, IN
	}

	private String fieldName;
	private Object value;
	private Operator operator;

	public DataFilter(String fieldName, Operator operator, Object value) {
		this.fieldName = fieldName;
		this.value = value;
		this.operator = operator;
	}

	public static Map<String, DataFilter> paser(Map<String, Object> searchParams) {

		Map<String, DataFilter> filters = new HashMap<String, DataFilter>();

		for (Entry<String, Object> entry : searchParams.entrySet()) {
			String key = entry.getKey();
			Object value = entry.getValue();

			if (StringUtils.isBlank((String) value)) {
				continue;
			}

			// 拆分operator与filedAttribute
			String[] names = StringUtils.split(key, DataFilterSeparator);
			if (names.length != 2) {
				throw new IllegalArgumentException(key + " is not a valid search filter name");
			}
			String filedName = names[1];
			Operator operator = Operator.valueOf(names[0]);

			// 创建searchFilter
			DataFilter filter = new DataFilter(filedName, operator, value);
			filters.put(key, filter);
		}

		return filters;
	}

	public String getFieldName() {
		return fieldName;
	}

	public void setFieldName(String fieldName) {
		this.fieldName = fieldName;
	}

	public Object getValue() {
		return value;
	}

	public void setValue(Object value) {
		this.value = value;
	}

	public Operator getOperator() {
		return operator;
	}

	public void setOperator(Operator operator) {
		this.operator = operator;
	}

}
